package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.nursing.domain.dto.CheckInApplyDto;
import com.zzyl.nursing.domain.dto.CheckInConfigDto;
import com.zzyl.nursing.domain.dto.CheckInContractDto;
import com.zzyl.nursing.domain.dto.CheckInElderDto;
import com.zzyl.nursing.domain.pojo.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.ICheckInService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 入住Service业务层处理
 * @author alexis
 * @date 2025-05-19
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    
    
    /**
     * 查询入住
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return checkInMapper.selectById(id);
    }
    
    /**
     * 查询入住列表
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }
    
    /**
     * 新增入住
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return checkInMapper.insert(checkIn);
    }
    
    /**
     * 修改入住
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return checkInMapper.updateById(checkIn);
    }
    
    /**
     * 批量删除入住
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }
    
    /**
     * 删除入住信息
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return checkInMapper.deleteById(id);
    }
    
    @Transactional
    @Override
    public void apply(CheckInApplyDto dto) {
        // 一、校验
        // 1.老人是否存在：select * from elder where name=？ and id_card_no=？ and status=1 （最终状态）
        CheckInElderDto checkInElderDto=dto.getCheckInElderDto();
        Elder elderDb=elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                                                    .eq(Elder::getName,checkInElderDto.getName())
                                                    .eq(Elder::getIdCardNo,checkInElderDto.getIdCardNo())
                                                    .eq(Elder::getStatus,1));
        if (ObjectUtil.isNotNull(elderDb)) {
            throw new ServiceException("老人已入住，不能重复申请");
        }
        // 二、新增
        // 1.床：更新
        CheckInConfigDto checkInConfigDto=dto.getCheckInConfigDto();
        Bed bed=bedMapper.selectById(checkInConfigDto.getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        // 2.老人：新增或者更新
        Elder insertOrUpdateElder=elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                                                                .eq(Elder::getName,checkInElderDto.getName())
                                                                .eq(Elder::getIdCardNo,checkInElderDto.getIdCardNo())
                                                                .ne(Elder::getStatus,1));
        Elder elder=new Elder();
        BeanUtil.copyProperties(checkInElderDto,elder);
        elder.setBedId(checkInConfigDto.getBedId());
        elder.setBedNumber(bed.getBedNumber());
        
        if (ObjectUtil.isNotNull(insertOrUpdateElder)) {
            // 说明：老人目前还在居住中，中间过程申请换房、换床、换人、换服务，这种场景只需要更新老人即可
            elder.setId(insertOrUpdateElder.getId());
            elderMapper.updateElder(elder);
        } else {
            // 说明：老人没有在系统数据中出现，是首次申请，这种场景就只需要新增老人即可
            elderMapper.insert(elder);
        }
        // 3.签约：新增
        CheckInContractDto checkInContractDto=dto.getCheckInContractDto();
        Contract contract=BeanUtil.toBean(checkInContractDto,Contract.class);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        contract.setStartDate(checkInConfigDto.getStartDate());
        contract.setEndDate(checkInConfigDto.getEndDate());
        contract.setStatus(checkInConfigDto.getStartDate()
                                           .isBefore(LocalDateTime.now()) ? 1 : 0);
        // 合同编号
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
        contractMapper.insert(contract);
        // 4.入住：新增
        CheckIn checkIn=BeanUtil.toBean(checkInConfigDto,CheckIn.class);
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkInMapper.insert(checkIn);
        // 5.入住配置：新增
        CheckInConfig checkInConfig=BeanUtil.toBean(checkInConfigDto,CheckInConfig.class);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }
}
